import emitter from '@ohos.events.emitter';
import util from '@ohos.util';
import { BusinessError } from '@kit.BasicServicesKit';

export class CancellableTask<T> {
  private readonly  eventId: string;

  constructor(eventId: string = util.generateRandomUUID(true)) {
    this.eventId = eventId;
  }

  run(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
    let _resolve: any = null;
    // 创建 Promise 并绑定事件监听
    return new Promise<T>((resolve, reject) => {
      // 注册一次性事件监听
      emitter.once(this.eventId, () => {
        reject({code:-1,message:"cancel promise"} as BusinessError<string>);
      });

      _resolve = (value: T) => {
        emitter.off(this.eventId)
        resolve(value);
      };

      // 执行主任务
      executor(_resolve, reject);
    });
  }

  cancel() {
    emitter.emit(this.eventId);
  }

  printListenerCount():number{
    const count = emitter.getListenerCount(this.eventId)
    console.debug("count = "+count)
    return count
  }
}